/**
 * Copyright (C) 2012  The CFuture Android SDK Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lurencun.android.toolkit.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.text.TextUtils;
import android.util.Xml;

/**
 * 
 * @author cfuture.chenyoca [桥下一粒砂] (chenyoca@163.com)
 * @date 2012-2-14
 */
public abstract class XmlParser {
	
	private StringBuffer mBuffer = new StringBuffer();
	
	private void parseXml(File file,DefaultHandler xml) throws SAXException,IOException{
		parseXml(new FileInputStream(file),xml);
	}
	
	private void parseXml(InputStream is,DefaultHandler xml) throws SAXException,IOException{
		android.util.Xml.parse(is,Xml.Encoding.UTF_8,xml);
	}
	
	/**
	 * 以文件形式解析XML文件
	 * @param file 需要进行解析的XML文件
	 */
	public void parse(File file){
		try{
			parseXml(file,new InnerXmlParse());
		}catch(Exception e){
			throw new RuntimeException(e.getMessage());
		}
	}
	
	/**
	 * 以输入流的方式解析XML文件
	 * @param is 需要解析的XML输入流
	 */
	public void parse(InputStream is){
		try{
			parseXml(is,new InnerXmlParse());
		}catch(Exception e){
			throw new RuntimeException(e.getMessage());
		}
	}
	
	/**
	 * XML开始结点
	 * @param tagName 结点名称
	 */
	protected abstract void onStartTag(String tagName);
	
	/**
	 * 解析到结束标签
	 * @param tagName
	 * @param data
	 */
	protected abstract void onEndTag(String tagName,StringBuffer data);
	
	/**
	 * XML解析引擎
	 * 
	 * @author cfuture.chenyoca [桥下一粒砂] (chenyoca@163.com)
	 * @date 2012-2-14
	 */
	private class InnerXmlParse extends DefaultHandler{
		public void startElement(String uri, String localName, String qName, Attributes attributes) 
				throws SAXException {
			mBuffer.setLength(0);
			onStartTag(qName);
		}
		
		@Override
		public void characters(char[] ch, int start, int length)throws SAXException {
			String data = new String(ch,start,length);
			if (!TextUtils.isEmpty(data)){
				mBuffer.append(data);
			}
		}
		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
			onEndTag(qName, mBuffer);
		}
	}
}
